package com.blockmeta.bbs.businesslibrary.net.rxjava;

import android.content.Context;
import android.text.TextUtils;

import com.blockmeta.bbs.baselibrary.utils.ToastUtil;
import com.blockmeta.bbs.baselibrary.utils.loading.ProgressBarUtil;
import com.blockmeta.bbs.businesslibrary.net.pojo.BaseCodeResponse;
import com.google.gson.Gson;
import com.google.gson.JsonParseException;

import io.reactivex.subscribers.ResourceSubscriber;
import okhttp3.ResponseBody;
import retrofit2.HttpException;

/**
 * @author AirThor
 * @date 2019/3/26.
 */
public abstract class CommonSubscriber<T> extends ResourceSubscriber<T> {
    private boolean showOtherException;
    private Context mContext;

    public CommonSubscriber(Context context) {
        mContext = context;
    }

    public CommonSubscriber(Context context, boolean showOtherException) {
        mContext = context;
        this.showOtherException = showOtherException;
    }

    @Override
    public void onComplete() {
        ProgressBarUtil.dismissProgress(mContext);
    }

    @Override
    public void onError(Throwable t) {
        ProgressBarUtil.dismissProgress(mContext);
        if(t instanceof JsonParseException) {
            ToastUtil.show("数据解析失败");
        }else if (t instanceof CustomException) {
            ToastUtil.show(t.getMessage());
        } else if (t instanceof HttpException){
            ResponseBody body = ((HttpException) t).response().errorBody();
            try {
                String bodyStr = body.string();
                BaseCodeResponse baseCodeResponse = new Gson().fromJson(bodyStr,BaseCodeResponse.class);
                if (!TextUtils.isEmpty(baseCodeResponse.msg)) {
                    ToastUtil.show(baseCodeResponse.msg);
                }
            } catch (Exception e) {
                e.printStackTrace();
                if (showOtherException){
                    ToastUtil.show(e.getMessage());
                }
            }
        }else if(showOtherException) {
            ToastUtil.show(t.getMessage());
        }
    }
}
